<!--
 * @Author: 秦福凯
 * @LastEditTime: 2025-05-22 09:31:48
 * @Description: 教师用户管理
-->

<template>
  <div class="u-search-header" >
    <el-form :model="search" >
      <el-form-item label="姓名" class="u-f-fl" label-width="68px">
        <u-input v-on:keyup.enter="enter" v-model="search.param.search.searchParam" placeholder="姓名、联系方式"></u-input>
      </el-form-item>
      <!-- <el-form-item label="状态" class="u-f-fl"  label-width="48px">
        <u-select @change="getSearch"  v-model="search.param.search.state" :data="statusData" style="width: 200px;"></u-select>
      </el-form-item>
      <el-form-item label="角色" class="u-f-fl"  label-width="48px">
        <u-select @change="getSearch"  v-model="search.param.search.roles" :data="[]" style="width: 200px;"></u-select>
      </el-form-item>
      <el-form-item label="部门" class="u-f-fl"  label-width="48px">
        <u-select @change="getSearch"  v-model="search.param.search.depts" :data="[]" style="width: 200px;"></u-select>
      </el-form-item> -->
      <el-form-item  class="u-f-fl" label-width="28px">
        <u-button type="primary" icon="Search" @click="getSearch">查询</u-button>
        <u-button icon="Delete" @click="reset"> 重置 </u-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="u-search-container">
    <div class="u-h-100">
      <div class="u-btns-box">
        <u-button :disabled="tabLaoding" type="primary" plain icon="Plus" @click="add">新增</u-button>
        <u-button :disabled="tabLaoding" type="primary" plain icon="CircleCheckFilled" @click="changeState(true)">批量启用</u-button>
        <u-button :disabled="tabLaoding" type="primary" plain icon="CircleCloseFilled" @click="changeState(false)">批量禁用</u-button>
        <u-button :disabled="tabLaoding" type="primary" plain icon="UploadFilled" @click="Upload">导入用户</u-button>
        <u-button :disabled="tabLaoding" type="primary" plain icon="folder" @click="exportallTeacherM">导出全部教师</u-button>

      </div>
        <u-table @changeSwitch="changeSwitch" v-loading="tabLaoding" :colunm="colunm" :data="TabData" @editBtnsClick="editBtnsClick" @selection-change="(data) => TabSelData.splice(0, TabSelData.length, ...data)"></u-table>
        <div class="u-common-pagination">
          <u-page-nation @pagination="paginationE" :total="total" :page="search.param.page"></u-page-nation>
        </div>
    </div>
  </div>


  <!-- 弹窗 -->
  <u-dialog :loadingBtn="formloading" :show="dialogShow" :title='dialogTitle' @close="dialogClose" width="70%"  @submit="submit">
    <u-form v-if="refrashForm" @changeForm="changeForm" ref="refform" v-loading="formloading" :element="formList" :form="form" >
      <template #password>
        <u-input show-password type="password" v-model="form.password" @change="changePassword"></u-input>
        <div style="margin-top: 8px;" >
          密码强弱:<el-segmented v-model="passwordStrange" :options="['弱','中','强']" disabled  size="default" />
        </div>
        <div style="margin-top: 8px;color: red;" >
          密码规则: 不能低于12位,密码中必须包含:大写字母、小写字母、数字、特殊字符(~!@#$^& +=|/?-)组成
        </div>
      </template>
    </u-form>
   </u-dialog>

   <!-- 导入 -->
  <u-file-upload :importLoading="importLoading" @fileimport="fileimport" :show="uploadShow" @dowmLoadFile="dowmLoadFile" @close="uploadShow = false"></u-file-upload>
  
</template>

<script setup>
import { ref, reactive,onMounted} from 'vue'
// 导入接口地址
import sys_servic from '@/api/system'

// 导入公共数据
import { useTecDataStore } from "@/store/teachinginstrument/index.js";
// 导入分页相关混合
import {PageMethod} from '@/components/common/mixin.ts'



// 公共数据取值
const TecDataStore = useTecDataStore()
const {page,pageSize,pageChane,} = PageMethod()

onMounted(() => {
  getSearch()
})
// 获取枚举
function getEnum(){
  formList.splice(0,formList.length,...formList2)
  getdeptRoleList()
}

const statusData = [
  {label:'启用',id:0},
  {label:'禁用',id:1},
]
const typeData = [
  {label:'男',id:0},
  {label:'女',id:1},
]
let roleData = reactive([])
// 重置搜索条件
function reset(){
  for(let i in search.param.search){
    search.param.search[i] = ''
  }
  getSearch()
}

function enter(){
  getSearch()
}

// 新增
let refrashForm = ref(true)
function add(){
  form.id = ''
  dialogShow.value = true
  dialogTitle.value = '新增'
  getallDeptList()
  refrashForm.value = false
  nextTick(() =>{
    refrashForm.value = true
  })
}
// 导入用户
let uploadShow = ref(false)
function Upload(){
  uploadShow.value = true
}
// 下载导入模板
function dowmLoadFile(){
  // const temp = new URL('@/assets/template/course.xls',import.meta.url)
  // let downloadElement = document.createElement('a');
  // downloadElement.href = temp 
  // downloadElement.download = '课程大纲导入模板.xls';
  // downloadElement.click(); //点击下载
  // downloadElement.remove()
    importLoading.value = true
  sys_servic.exportTeacherTemplate(search).then(res =>{
    importLoading.value = false
  })
}

// 导入
let importLoading = ref(false)
function fileimport(file){
  let params = new FormData();
    params.append('file', file.raw)
    importLoading.value = true
    sys_servic.uploadTeacherTemplate(params).then(res =>{
      importLoading.value = false
      if(res.data.code == 200){
       uploadShow.value = false
        ElMessage.success(res.data.msg)
       getSearch()
      }else{
        ElMessage.warning(res.data.msg)
      }
    })
}

// 查询相关变量
let search = reactive({
  ...TecDataStore.comObj,
  param:{
    page:page,
    pageSize:pageSize,
    search:{
      // realName:'',
      // state:'',
      // roles:'',
      // depts:'',
      searchParam:''
    }
  }
})
let tabLaoding = ref(false)
let total = ref(0)

let colunm = reactive([
  {type:'selection'},
  {label:'序号',type:'index',width:60},
  {label:'教工编号',key:'teacherNo',width:120},
  {label:'姓名',key:'realName',width:120,},
  // {label:'性别',key:'deviceName',width:80,ctype:'dict',dict:[
  //   {label:'男',id:0}
  // ]},
  // {label:'身份证号码',key:'idCard',width:180,ctype:'tm',tmType:'idCard'},
  {label:'身份证号码',key:'idCard',width:180,},
  // {label:'手机号',key:'phone',width:160,ctype:'tm',tmType:'phone'},
  {label:'手机号',key:'phone',width:160,},
  {label:'部门',key:'deptName',width:90},
  {label:'角色',key:'roleId',width:120,ctype:'dict',dict:[]},
  // {label:'邮箱',key:'lockerName',width:160,ctype:'tm',tmType:'email'},
  {label:'状态',key:'state',width:160,ctype:'switch',activeText:'启用',inactiveText:'禁用'},
  {label:'操作',key:'cz',minWidth:280,ctype:'edit',
    data:[
      {label:'编辑',icon:'Edit'},
      {label:'删除',icon:'Delete'},
      {label:'重置密码',icon:'RefreshRight'},
    ]
  },
])
let TabData = reactive([
  // {name:'秦福凯',deviceName:0,typeId:'18545845877',quantity:'5845874558458458748',lockerName:'985485125@qq.com'},
])

// 查询
function getSearch(){
  return
  tabLaoding.value = true
  sys_servic.teacherUserListPage(search).then(res =>{
    tabLaoding.value = false
    if(res.data.code == 200){
      TabData = res.data.data.records
      total.value = res.data.data.total
     
    }else{
      ElMessage.warning(res.data.msg)
    }
  })
}

// 分页组件切换
function paginationE(val){
  search.param.page = val.page
  search.param.pageSize = val.limit
  getSearch()
}

// 表格选择的数据
let TabSelData = reactive([])

function changeSwitch(k,v,r){
  let parmas = {
    ...TecDataStore.comObj,
    param:{
      state:v,
      userIds:[],
    }
  }
  parmas.param.userIds[0] = r.sysUserId
  sys_servic.changeUserStat(parmas).then(res =>{
  if(res.data.code == 200){
    ElMessage.success(res.data.msg)
    getSearch()
  }else{
    ElMessage.warning(res.data.msg)
  }
 })
}

// 表格点击事件
function editBtnsClick(label,row){
  if(label == '删除'){
  ElMessageBox.confirm(
  '确认删除选中数据?删除将不可恢复请谨慎操作',
  '系统提示',
  {
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
  }
  ).then(() =>{
    sys_servic.delTeacher({...TecDataStore.comObj,param:row.id}).then(res =>{
      if(res.data.code == 200){
        ElMessage.success('删除成功!')
        getSearch()
      }else{
        ElMessage.warning(res.data.msg)
      }
  })
  })
}
  if(label == '编辑'){
    dialogTitle.value = '修改用户'
    dialogShow.value = true
    getallDeptList(row.deptId)
    getEditData(row)
  }
  if(label == '重置密码'){
    ElMessageBox.confirm(
    '确认重置密码？',
    '系统提示',
    {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    }
  ).then(() =>{
    sys_servic.changeUserPassword({...TecDataStore.comObj,param:{
      type:0,password:'',sysUserId:row.sysUserId
    }}).then(res =>{
      if(res.data.code == 200){
        ElMessageBox.confirm(
        '重置成功',
        '系统提示',
        {
        confirmButtonText: '确认',
        showCancelButton: false,
        type: 'success',
        }
      )
        getSearch()
      }else{
        ElMessage.warning(res.data.msg)
      }
  })
  })
  }
}
// 获取回显数据
function getEditData(val){
  formloading.value = true
  sys_servic.getTeacherById({...TecDataStore.comObj,param:val.id}).then(res =>{
    formloading.value = false
    if(res.data.code == 200){
      let data = res.data.data
      for(let i in form){
        if(data[i]){
          form[i] = data[i]
        }
      }
      form.id = val.sysUserId
      refrashForm.value = false
      nextTick(() =>{
        refrashForm.value = true
      })
    }else{
      ElMessage.warning(res.data.msg)
    }
  })
  formList = formList.filter((v,i,a) =>{
    return v.key !== 'password' && v.key !== 'password2'
  })

  return
 
 
}

// 弹窗相关参数
let dialogShow = ref(false)
let dialogTitle = ref('弹窗标题')

// 弹窗里的表单参数
let form = reactive({
  id:"",
  realName:'',
  teacherNo:0,
  phone:'',
  idCard:'',
  password:'',
  password2:'',
  roleId:'',
  deptId:'',
})
let formList = reactive([])
let formList2 = reactive([
  {label:'姓名:',key:'realName',type:'input',placeholder:"",sp:12,re:true},
  {label:'教工编号:',key:'teacherNo',type:'numInput',placeholder:"",sp:12,},
  {label:'联系方式:',key:'phone',type:'input',placeholder:"",sp:12,re:true,rule:[
  { required: true,min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' },
  ],},
  {label:'身份证:',key:'idCard',type:'input',placeholder:"",sp:12,re:true,
  rule:[{ required: true,min: 18, max: 18, message: '请输入18位身份证号', trigger: 'blur' },],},
  {label:'密码:',key:'password',type:'slot',placeholder:"",sp:12,re:true},
  {label:'确认密码:',key:'password2',type:'password',placeholder:"",sp:12,re:true,rule:[
    { validator: (rules,value,callback) =>{
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== form.password) {
        callback(new Error("两次输入密码不一致请重新输入"))
        // form.password2 = ''
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ]},
  {label:'部门:',key:'deptId',type:'select',placeholder:"",sp:12,re:true,data:[]},
  {label:'角色:',key:'roleId',type:'select',placeholder:"",sp:12,re:true},
])
const refform = ref(null)
let formloading = ref(false)
let imgsrc = ref(null)
  

// 获取所有部门列表
function getallDeptList(val){
  formList[formList.findIndex(i => i.key == 'deptId')].loading = true
  sys_servic.allDeptList({...TecDataStore.comObj,param:''}).then(res =>{
    formList[formList.findIndex(i => i.key == 'deptId')].loading = false
    if(res.data.code == 200){
    
      let data = JSON.parse(JSON.stringify(res.data.data))
      data.forEach(item =>{
        item.label = item.name
      })
      formList[formList.findIndex(i => i.key == 'deptId')].data = data
    }else{
      ElMessage.warning(res.data.msg)
    }
  })
}

// 查看部门包含的角色列表
function getdeptRoleList(){
  formList[formList.findIndex(i => i.key == 'roleId')].loading = true
  sys_servic.deptRoleList({...TecDataStore.comObj,param:''}).then(res =>{
    formList[formList.findIndex(i => i.key == 'roleId')].loading = false
    if(res.data.code == 200){
      let data = JSON.parse(JSON.stringify(res.data.data))
      data.forEach(item =>{
        item.label = item.roleName
      })
        data.map(i => i.content = i.label)
        colunm[colunm.findIndex(i => i.key == 'roleId')].dict = data
        formList[formList.findIndex(i => i.key == 'roleId')].data = data
    
    }else{
      ElMessage.warning(res.data.msg)
    }
  })
}

function changeForm(k,v){

}

let strength = ref(0)
function changePassword(v){
   strength.value = passwordStrength(v)
   console.log(strength.value);
   if(strength.value <= 2){
    passwordStrange.value = '弱'
   }
   if(strength.value === 4){
    passwordStrange.value = '中'
   }
   if(strength.value  > 4){
    passwordStrange.value = '强'
   }
 
}

// 验证密码强弱
let passwordStrange = ref('弱')
const passwordStrength = (password) => {
  let strength = 0;
  if (password.length >= 12) strength += 1;
  if (password.match(/[a-z]/)) strength += 1;
  if (password.match(/[A-Z]/)) strength += 1;
  if (password.match(/[0-9]/)) strength += 1;
  if (password.match(/[^a-zA-Z0-9]/)) strength += 1;
  return strength;
  };

// 弹窗提交
function submit(){
  refform.value.soform.validate((vali) =>{
    if(!vali){
      ElMessage.warning('请将表单填写完整!')
    }else{
      // if(passwordStrange.value !== '强'){
      //   ElMessage.warning('密码规则：不能低于12位,密码中必须包含：大写字母、小写字母、数字 、 特殊字符(~!@#$^&_+=|/?-)组成')
      //   return
      // }
      let parmas = {
        ...TecDataStore.comObj,
        param:{
          ...JSON.parse(JSON.stringify(form)),
        }
      }
      console.log(parmas);
     const url = parmas.param.id == '' || parmas.param.id == undefined ? 'addTeacher' : 'updateTeacher'
      formloading.value = true
      sys_servic[url](parmas).then(res =>{
        formloading.value = false
        if(res.data.code == 200){
          ElMessage.success(res.data.msg)
          dialogShow.value = false
          getSearch()
        }else{
          ElMessage.warning(res.data.msg)
        }
    })
    }
  })
}

// 弹窗关闭
function dialogClose(){
  dialogShow.value = false
  // 清理表单缓存
  refform.value.soform.resetFields()
  for(let i in form){
    form[i] = ''
  }
  formList.splice(0,formList.length,...formList2)
}

// 批量启用/停用
function changeState(type){
  if(TabSelData.length == 0){
    ElMessage.warning('请至少选择一条数据!')
    return
  }
  let ids = TabSelData.map(i => i.sysUserId)
  let parmas = {
    ...TecDataStore.comObj,
    param:{
      state:0,
      userIds:ids,
    }
  }
  if(type){
    // 启用
    parmas.param.state = 1
  }else{
    // 停用
    parmas.param.state = 0
  }
 sys_servic.changeUserStat(parmas).then(res =>{
  if(res.data.code == 200){
    ElMessage.success(res.data.msg)
    getSearch()
  }else{
    ElMessage.warning(res.data.msg)
  }
 })

 
}


// 导出全部教师
function exportallTeacherM(){
  tabLaoding.value = true
  sys_servic.exportAllTeacher().then(res =>{
    tabLaoding.value = false
  })
}




// getEnum()

</script>
<style lang='scss' scoped>

</style>